package cn.com.czpb.client.module.personal.acticity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.com.czpb.client.R;
import cn.com.czpb.client.app.ToolBarActivityWhite;
import cn.com.czpb.client.custorm.CircleImageView;
import cn.com.czpb.client.custorm.CustomProgressDialog;
import cn.com.czpb.client.model.news.EmptyEntityList;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class ForgetPWActivity extends ToolBarActivityWhite implements View.OnFocusChangeListener {
    private static final String TAG = "ForgetPWActivity";
    @BindView(R.id.title_toolbar)
    TextView title_stilte_layout;
    @BindView(R.id.phone_et_findpw_fragment)
    EditText phone_et_findpw_fragment;
    @BindView(R.id.code_et_findpw_fragment)
    EditText code_et_findpw_fragment;
    private String phoneNumber;
    private String code;
    @BindView(R.id.tv_findpw_fragment)
    volatile TextView tv_findpw_fragment;
    @BindView(R.id.fpb_ll_veify)
    LinearLayout fpb_ll_veify;//验证码
    @BindView(R.id.reset_ll_findpw)
    LinearLayout reset_ll_findpw;//找回密码

    @BindView(R.id.pw_1_findpw)
    EditText pw_1_findpw;
    @BindView(R.id.pw_2_findpw)
    EditText pw_2_findpw;

    @BindView(R.id.tv_right_toolbar)
    TextView right_stitle_layout;
    @BindView(R.id.closed01)
    CircleImageView closed01;
    @BindView(R.id.closed02)
    CircleImageView closed02;
    @BindView(R.id.closed03)
    CircleImageView closed03;
    @BindView(R.id.closed04)
    CircleImageView closed04;
    int type;
    private Timer timer;
    boolean ishow[]={false,false,false,false};
    private int t = 60;
    private boolean isflag = false;
    private CustomProgressDialog dialog; // 载入中对话框
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 333: {
                    try {
                        tv_findpw_fragment.setText(t + "秒后重发");
                        t--;
                        if (t < 0) {
                            resetTimer();
                        }
                        disMissDialog();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
                break;
                case 444: {

                    verifyCorrect();
                    TUtils.toast("验证成功");
                }
                break;
                case 555: {
                    TUtils.toast("验证码错误");
                    code_et_findpw_fragment.setText("");

                    resetTimer();
                }
                break;
                case 445: {
                    TUtils.toast("验证码获取成功");

                    startTime();// 开启定时器
                }
                break;
                case 446: {
                    TUtils.toast("验证码获取失败");

                    resetTimer();
                }
                break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        right_stitle_layout.setVisibility(View.VISIBLE);
        right_stitle_layout.setText("下一步");
    }

    private void init() {
        title_stilte_layout.setText("找回密码");

        SMSSDK.registerEventHandler(new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        //验证码获取成功
                        handler.sendEmptyMessage(445);
                    } else if (result == SMSSDK.RESULT_ERROR) {
                        handler.sendEmptyMessage(446);
                    }
                } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        handler.sendEmptyMessage(444);
                    } else if (result == SMSSDK.RESULT_ERROR) {
                        handler.sendEmptyMessage(555);
                    }
                }
            }
        });
    }

    @Override
    public int setMyContentView() {
        return R.layout.activity_forget_pw;
    }


    private void verifyCorrect() {
        right_stitle_layout.setText("完成");
        isflag = true;
        fpb_ll_veify.setVisibility(View.GONE);
        reset_ll_findpw.setVisibility(View.VISIBLE);

    }

    private void startTime() {

        phone_et_findpw_fragment.setEnabled(false);
        tv_findpw_fragment.setClickable(false);
        if (timer != null) {
            timer.cancel();
        }
        tv_findpw_fragment.setTextColor(getResources().getColor(R.color.color_bdbdbd));
        timer = new Timer();
        TimerTask tt = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(333);
            }
        };
        timer.schedule(tt, 0, 1000);

    }

    private void resetTimer() {
        disMissDialog();
        if (null != timer) {
            timer.cancel();
        }
        tv_findpw_fragment.setText("重新获取");
        tv_findpw_fragment.setClickable(true);
        tv_findpw_fragment.setTextColor(getResources().getColor(R.color.color_df3031));
        phone_et_findpw_fragment.setEnabled(true);
        t = 60;
    }
    @OnClick({R.id.closed01,R.id.closed02})
    public void Closed(View view){
        switch (view.getId()){
            case R.id.closed01:
                phone_et_findpw_fragment.setText("");
                closed01.setVisibility(View.GONE);
                break;
            case R.id.closed02:
                code_et_findpw_fragment.setText("");
                closed02.setVisibility(View.GONE);
                break;
            case R.id.closed03:
                pw_1_findpw.setText("");
                closed03.setVisibility(View.GONE);
                break;
            case R.id.closed04:
                pw_2_findpw.setText("");
                closed04.setVisibility(View.GONE);
                break;
        }
    }
    @OnClick(R.id.tv_findpw_fragment)
    public void getCode(View view) {

        //验证码验证

        phoneNumber = phone_et_findpw_fragment.getText().toString().trim();
        if (phoneNumber == null || "".equals(phoneNumber)) {
            TUtils.toast("请输入手机号！");
            return;
        }
        if (phoneNumber.length() != 11) {
            TUtils.toast("手机号位数不对!");
            return;
        }
        tv_findpw_fragment.setClickable(false);
        SMSSDK.getVerificationCode("86", phoneNumber);

    }

    @OnClick(R.id.tv_right_toolbar)
    public void Verify(View v) {
        if (isflag == false) {
            String s = code_et_findpw_fragment.getText().toString().trim();
            if (s == null || "".equals(s)) {
                TUtils.toast("请输入验证码！");
                return;
            }
            SMSSDK.submitVerificationCode("86", phoneNumber, s);
            showDialog();
        } else {
            //修改新密码
            phoneNumber = phone_et_findpw_fragment.getText().toString().trim();
            phoneNumber = "13621089522";
            String s = pw_1_findpw.getText().toString().trim();
            String s2 = pw_2_findpw.getText().toString().trim();
            if (s == null || "".equals(s)) {
                TUtils.toast("请输入密码");
                return;
            }
            if (s.length() < 6) {
                TUtils.toast("密码不能太短");
                return;
            }
            if (s.length() > 12) {
                TUtils.toast("密码不能太长");
                return;
            }
            if (s2 == null || "".equals(s2)) {
                TUtils.toast("请输入确认密码");
                return;
            }
            if (!s.equals(s2)) {
                TUtils.toast("俩次密码不一致！");
                pw_1_findpw.setText("");
                pw_2_findpw.setText("");
                return;
            }
            showDialog();
            findPwd(phoneNumber, s2);
        }

    }

    @Override
    public void initView() {
        //手机号
        phone_et_findpw_fragment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() <= 0) {

                    closed01.setVisibility(View.GONE);
                    ishow[0]=false;
                } else {
                    closed01.setVisibility(View.VISIBLE);
                    ishow[0]=true;
                }
            }
        });
        code_et_findpw_fragment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() <= 0) {
                    closed02.setVisibility(View.GONE);
                    ishow[1]=false;
                } else {
                    closed02.setVisibility(View.VISIBLE);
                    ishow[1]=true;
                }
            }
        });
        //普通登录输入账号
        pw_1_findpw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (editable.length() <= 0) {
                    closed03.setVisibility(View.GONE);
                    ishow[2]=false;
                } else {
                    closed03.setVisibility(View.VISIBLE);
                    ishow[2]=true;
                }
            }
        });
        pw_2_findpw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() <= 0) {
                    closed04.setVisibility(View.GONE);
                    ishow[3]=false;
                } else {
                    closed04.setVisibility(View.VISIBLE);
                    ishow[3]=true;
                }
            }
        });
    }

    private void findPwd(String phone, String newPw) {
        Map<String, String> map = new HashMap<>();
        map.put("mobile", phone);

        map.put("password", newPw);
        Factory.provideHttpService().changePassWord(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntityList, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntityList emptyEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntityList>() {
                    @Override
                    public void call(EmptyEntityList emptyEntity) {
                        disMissDialog();
                        LogUtils.e("code--" + emptyEntity.code);
                        TUtils.toast(emptyEntity.msg);
                        activity.finish();
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG, "throwable: " + throwable.getMessage());
                    }
                });
    }


    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
        // 销毁回调监听接口
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();
    }

    @Override
    public void initData() {
        code_et_findpw_fragment.setOnFocusChangeListener(this);
        phone_et_findpw_fragment.setOnFocusChangeListener(this);
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        switch (view.getId()) {
            case R.id.code_et_findpw_fragment:
                if (!b) {
//                    closed02.setVisibility(View.GONE);
                    if(closed02!=null) {
                        closed02.setVisibility(View.GONE);
                    }
                }else if (ishow[1]){
                    closed02.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.phone_et_findpw_fragment:
                if (!b) {
//                    closed01.setVisibility(View.GONE);
                    if (closed01!=null){
                        closed01.setVisibility(View.GONE);
                    }
                }else if (ishow[0]){
                    closed01.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.pw_1_findpw:
                if (!b) {
//                    closed03.setVisibility(View.GONE);
                    if (closed03!=null){
                        closed03.setVisibility(View.GONE);
                    }
                }else if (ishow[2]){
                    closed03.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.pw_2_findpw:
                if (!b) {
//                    closed04.setVisibility(View.GONE);
                    if (closed04!=null){
                        closed04.setVisibility(View.GONE);
                    }
                }else if (ishow[3]){
                    closed04.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

}


